import { ref } from 'vue';
import type { Ref } from 'vue';

function useStorage<T>(key: string, defaultValue: T): {
  value: Ref<T>;
  setValue: (val?: T) => void;
} {
  // 检查是否在浏览器环境
  const isClient = typeof window !== 'undefined'
  // 获取存储的值
  const getStorage = (): T => {
    if (!isClient) {
      return defaultValue;
    }
    const val = localStorage.getItem(key);
    if (val) {
      try {
        return JSON.parse(val);
      } catch {
        return defaultValue;
      }
    }
    return defaultValue;
  };

  // 创建响应式引用
  const value = ref<T>(getStorage());

  // 设置值的函数
  const setValue = (val?: T) => {
    if (!isClient) {
      return;
    }
    if (val === undefined) {
      localStorage.removeItem(key);
      value.value = defaultValue;
    } else {
      localStorage.setItem(key, JSON.stringify(val));
      value.value = val;
    }
  };

  return {
    value,
    setValue,
  };
}


export default useStorage;